import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { jwtConstants } from '../constants/constants';
import { Request } from 'express';
import { UsersService } from 'src/service/HTTPService/users/users.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private jwtService: JwtService, private usersService: UsersService) {

  }

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    // console.log(`[AuthGuard] canActivate - request:`,request)
    const token = this.extractTokenFromHeader(request);
    if (this.isDisabledAuth(context)) {
      return true;
    }
    if (!token) {
      throw new UnauthorizedException();
    }

    try {
      const payload = await this.jwtService.verifyAsync(
        token,
        {
          secret: jwtConstants.secret
        }
      );

      request['user'] = payload;
      if (!await this.usersService.verifyToken(token, payload.id)) {
        throw new UnauthorizedException();
      }
    } catch (error) {
      throw new UnauthorizedException();
    }

    return true;
  }

  private extractTokenFromHeader(request: Request): string | undefined {

    const [type, token] = request.headers.authorization?.split(' ') ?? [];
    return type === 'Bearer' ? token : undefined;
  }
  private isDisabledAuth(context: ExecutionContext): boolean {
    const controller = context.getHandler();
    const disableAuthMeta = Reflect.getMetadata('disableAuth', controller);
    if (disableAuthMeta === true) {
      return true;
    }

    const method = context.getHandler();
    const disableAuthMetaMethod = Reflect.getMetadata('disableAuth', method);
    if (disableAuthMetaMethod === true) {
      return true;
    }

    return false;
  }
}